<?php

namespace backend\components;

use Yii;
use yii\base\Component;

class AdminAccessLog extends Component
{

    public $logCategory = "adminAccessLog";
    public $guestUserName = "*GUEST*";

    /**
     * @param \yii\base\Event $event
     */
    public function addByAfterRequestEvent($event)
    {
        $request = $event->sender->get('request');
        $requestUrl = $request->getUrl();
        $requestMethod = $request->getMethod();
        $requestMethodParam = $request->getBodyParams();

        $userAgent = $request->getUserAgent();

        $username = $this->getUsername();

        $logContent = json_encode([$username,$requestUrl,$requestMethod,$requestMethodParam,$userAgent],JSON_UNESCAPED_UNICODE);

        $logTraceLevel = Yii::$app->getLog()->traceLevel;
        if($logTraceLevel !=0 ) Yii::$app->getLog()->traceLevel = 0;
        Yii::info($logContent,$this->logCategory);
        if($logTraceLevel !=0 ) Yii::$app->getLog()->traceLevel = $logTraceLevel;
    }

    public function getUsername()
    {
        if(Yii::$app->getUser()->isGuest){
            $username = $this->guestUserName;
        }else{
            $username = Yii::$app->getUser()->getIdentity()->username.'('.Yii::$app->getUser()->getId().')';
        }
        return $username;
    }
}
